﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers.Provider;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “内容对话框”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace Rainbow_Game_Fans
{
    public sealed partial class ContentDialog_Donate : ContentDialog
    {
        
        ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        public  ContentDialog_Donate()
        {
            this.InitializeComponent();
        }

        private async  void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            var uri = new Uri("http://lab.alipay.com");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
        }
        string BuyMessage;
        string dialog_PrimaryButton_Text;
        string producctID = "Rainbow_Game_Fans_Donate";
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Buy();  
        }

        async void Buy()//消耗型物品 购买
        {
            //Log("Buying Product 1...", NotifyType.StatusMessage);
            try
            {
                PurchaseResults purchaseResults = await CurrentApp.RequestProductPurchaseAsync(producctID);
                switch (purchaseResults.Status)
                {
                    case ProductPurchaseStatus.Succeeded:
                        BuyMessage = "购买成功，谢谢支持";
                        dialog_PrimaryButton_Text = "确定";
                        
                        //GrantFeatureLocally(producctID, purchaseResults.TransactionId);
                        FulfillproducctID(producctID, purchaseResults.TransactionId);
                        break;
                    case ProductPurchaseStatus.NotFulfilled:
                        //    if (!IsLocallyFulfilled(producctID, purchaseResults.TransactionId))
                        //    {
                        //        GrantFeatureLocally(producctID, purchaseResults.TransactionId);
                        //    }
                        BuyMessage = "购买失败，请重试";
                        dialog_PrimaryButton_Text = "重试";
                        FulfillproducctID(producctID, purchaseResults.TransactionId);
                        break;
                    case ProductPurchaseStatus.NotPurchased:
                        //Log("Product 1 was not purchased.", NotifyType.StatusMessage);
                        BuyMessage = "购买失败，请重试";
                        dialog_PrimaryButton_Text = "重试";
                        break;
                }
            }
            catch (Exception)
            {
                //Log("Unable to buy Product 1.", NotifyType.ErrorMessage);
                BuyMessage = "无法购买，请重试";
                dialog_PrimaryButton_Text = "重试";
            }
            ShowDialog_Exit();
        }

        private async void FulfillproducctID(string productId, Guid transactionId)  //消耗掉物品，以便再次购买
        {
            try
            {
                FulfillmentResult result = await CurrentApp.ReportConsumableFulfillmentAsync(productId, transactionId);
                //switch (result)
                //{
                //    case FulfillmentResult.Succeeded:
                //        //Log("You bought and fulfilled product 1.", NotifyType.StatusMessage);

                //        break;
                //    case FulfillmentResult.NothingToFulfill:
                //        Log("There is no purchased product 1 to fulfill.", NotifyType.StatusMessage);
                //        break;
                //    case FulfillmentResult.PurchasePending:
                //        Log("You bought product 1. The purchase is pending so we cannot fulfill the product.", NotifyType.StatusMessage);
                //        break;
                //    case FulfillmentResult.PurchaseReverted:
                //        Log("You bought product 1. But your purchase has been reverted.", NotifyType.StatusMessage);
                //        // Since the user's purchase was revoked, they got their money back.
                //        // You may want to revoke the user's access to the consumable content that was granted.
                //        break;
                //    case FulfillmentResult.ServerError:
                //        Log("You bought product 1. There was an error when fulfilling.", NotifyType.StatusMessage);
                //        break;
                //}
            }
            catch (Exception)
            {
                //Log("You bought Product 1. There was an error when fulfilling.", NotifyType.ErrorMessage);
            }
            //ShowDialog_Exit();
        }

        //private void Log(string message, NotifyType type)
        //{
        //    string logMessage = message + "\n\n" + GetFulfillmentResults();
        //    rootPage.NotifyUser(logMessage, type);
        //}

        //private int numberOfConsumablesPurchased = 0;
        //private Dictionary<string, List<Guid>> grantedConsumableTransactionIds = new Dictionary<string, List<Guid>>();

        //private string GetFulfillmentResults()
        //{
        //    string message = "Product 1 has been fulfilled " + numberOfConsumablesPurchased + " time" + (numberOfConsumablesPurchased == 1 ? "" : "s") + ".";
        //    return message;
        //}

        //private void GrantFeatureLocally(string productId, Guid transactionId)
        //{
        //    if (!grantedConsumableTransactionIds.ContainsKey(productId))
        //    {
        //        grantedConsumableTransactionIds.Add(productId, new List<Guid>());
        //    }
        //    grantedConsumableTransactionIds[productId].Add(transactionId);

        //    // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
        //    numberOfConsumablesPurchased++;
        //}

        //private Boolean IsLocallyFulfilled(string productId, Guid transactionId)
        //{
        //    return grantedConsumableTransactionIds.ContainsKey(productId) && grantedConsumableTransactionIds[productId].Contains(transactionId);
        //}

        async void ShowDialog_Exit()
        {

            ContentDialog dialog = new ContentDialog()
            {
                Title = "购买确认", //标题
                Content = BuyMessage,//内容
                FullSizeDesired = false,  //是否全屏展示
                PrimaryButtonText = dialog_PrimaryButton_Text,//第一个按钮内容
                SecondaryButtonText = "取消"
            };
            dialog.Background = new SolidColorBrush(Colors.Red);
            if (localSettings.Values["slider_brightness_Value"] != null)
            {
                dialog.Opacity = (double)localSettings.Values["slider_brightness_Value"];
            }
            dialog.SecondaryButtonClick += dialog_SecondaryButtonClick;//第二个按钮单击事件
            dialog.PrimaryButtonClick += dialog_PrimaryButtonClick;

            ContentDialogResult result = await dialog.ShowAsync();
            if (result == ContentDialogResult.Primary) { } //处理第一个按钮的返回
            else if (result == ContentDialogResult.Secondary) { }//处理第二个按钮的返回

        }
        void dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            //await new MessageDialog("您选择了第一个按钮").ShowAsync();
            if (dialog_PrimaryButton_Text == "重试")
                Buy();
            //else 
            //    this.navigationHelper.GoBack();
        }
        void dialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            //await new MessageDialog("您选择了第二个按钮").ShowAsync();
        }

       
    }
}
